package com.fcscs.cservice.ws.endpoint;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;

import com.fcscs.core.common.MainEnums;
import com.fcscs.core.domain.PropertyEntity;
import com.fcscs.core.util.CommonUtil;
import com.fcscs.cservice.common.CServiceCommonEnums.FileRequestType;
import com.fcscs.cservice.common.CServiceCommonEnums.ResourceKeyEnum;
import com.fcscs.cservice.common.CServiceCommonEnums.ModuleEnum;
import com.fcscs.cservice.common.CServiceCommonEnums.ThemeItemType;
import com.fcscs.cservice.domain.Restaurant;
import com.fcscs.cservice.domain.RestaurantPicture;
import com.fcscs.cservice.domain.model.Advertisement;
import com.fcscs.cservice.domain.model.CountryView;
import com.fcscs.cservice.domain.model.EditabilityConf;
import com.fcscs.cservice.domain.model.MainMenuItemView;
import com.fcscs.cservice.domain.model.ReservationConfView;
import com.fcscs.cservice.domain.model.ResourceView;
import com.fcscs.cservice.domain.model.ThemeItem;
import com.fcscs.cservice.domain.model.StateView;
import com.fcscs.cservice.service.CServiceCommonManager;
import com.fcscs.cservice.service.RestaurantManager;
import com.fcscs.cservice.service.RestaurantPictureManager;
import com.fcscs.cservice.ws.WebServiceUtils;
import com.fcscs.cservice.ws.schema.commonservice.GetAdvertisementsRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetAdvertisementsResponse;
import com.fcscs.cservice.ws.schema.commonservice.GetCountriesRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetCountriesResponse;
import com.fcscs.cservice.ws.schema.commonservice.GetFieldEditConfRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetFieldEditConfResponse;
import com.fcscs.cservice.ws.schema.commonservice.GetFileRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetFileResponse;
import com.fcscs.cservice.ws.schema.commonservice.GetReservationConfRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetReservationConfResponse;
import com.fcscs.cservice.ws.schema.commonservice.GetResourceViewRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetResourceViewResponse;
import com.fcscs.cservice.ws.schema.commonservice.GetStatesRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetStatesResponse;
import com.fcscs.cservice.ws.schema.commonservice.GetMainMenuRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetMainMenuResponse;
import com.fcscs.cservice.ws.schema.commonservice.GetThemeRequest;
import com.fcscs.cservice.ws.schema.commonservice.GetThemeResponse;
import com.fcscs.share.domain.nonexport.RCAttachment;
import com.fcscs.share.service.MiscDBManager;

@Endpoint
public class CommonServiceEndpoint {

	@Autowired
	CServiceCommonManager ccMgr;

	@Autowired
	MiscDBManager miscMgr;

	@Autowired
	RestaurantManager restMgr;

	@Autowired
	RestaurantPictureManager restPicMgr;

	@PayloadRoot(localPart = CServiceWSConstants.GET_CONT_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetCountriesResponse getCountries(@RequestPayload GetCountriesRequest req) {
		long propId = CommonUtil.getWsSessionPropertyId();
		GetCountriesResponse resp = new GetCountriesResponse();
		List<CountryView> cList = ccMgr.getCountryViewList(propId);
		resp.setCountryList(cList);
		return resp;
	}

	@PayloadRoot(localPart = CServiceWSConstants.GET_STA_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetStatesResponse getReservationConfigurations(@RequestPayload GetStatesRequest req) {
		GetStatesResponse resp = new GetStatesResponse();
		List<StateView> sList = ccMgr.getStateViewList(req.getCountryId());
		resp.setStateList(sList);
		return resp;
	}

	@PayloadRoot(localPart = CServiceWSConstants.GET_RSV_CONF_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetReservationConfResponse getReservationConfigurations(@RequestPayload GetReservationConfRequest req) {
		long orgId = CommonUtil.getWsSessionOrgId();
		long propId = CommonUtil.getWsSessionPropertyId();
		GetReservationConfResponse resp = new GetReservationConfResponse();
		ReservationConfView conf = ccMgr.getRsvConfView(orgId, propId);
		resp.setReservationConf(conf);
		return resp;
	}

	@Value("/dummy/advertisement_banner.png")
	Resource dummyAd;

	@PayloadRoot(localPart = CServiceWSConstants.GET_ADVERT_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetAdvertisementsResponse getAdvertisements(@RequestPayload GetAdvertisementsRequest req) {

		GetAdvertisementsResponse resp = new GetAdvertisementsResponse();
		List<Advertisement> list = new ArrayList<Advertisement>();
		Advertisement ad = new Advertisement();
		ad.setAdvertismentId(1L);

		FileInputStream fin = null;
		byte[] fileContent = null;
		try {
			fin = new FileInputStream(dummyAd.getFile());
			fileContent = new byte[(int) dummyAd.getFile().length()];
			fin.read(fileContent);
			fin.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		ad.setBannerFile(WebServiceUtils.convertToString(fileContent));
		ad.setUrl("http://www.fcscs.com");
		list.add(ad);
		resp.setAdvertisementList(list);

		return resp;
	}
	
	private boolean isLegalAccess(PropertyEntity entity) {
		long orgId = CommonUtil.getWsSessionOrgId();
		if (entity != null && orgId != entity.getOrgId()) {
			return false;
		}
		return true;
	}

	@PayloadRoot(localPart = CServiceWSConstants.GET_FILE_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetFileResponse getFile(@RequestPayload GetFileRequest req) {
		GetFileResponse resp = new GetFileResponse();

		String file = null;

		try {
			FileRequestType type = FileRequestType.valueOf(req.getFileType());
			switch (type) {
			case REST_LOGO:
				Restaurant pic = restMgr.get(req.getFileId());
				if (isLegalAccess(pic)) {
					file = WebServiceUtils.convertToString(pic.getLogo());
				}
				break;
			case REST_PHOTO:
				RestaurantPicture pic1 = restPicMgr.get(req.getFileId());
				if (isLegalAccess(pic1)) {
					file = WebServiceUtils.convertToString(pic1.getPic());
				}
				break;
			case RC_INITIALS:
				RCAttachment att = miscMgr.getRCAttachment(req.getFileId());
				if (isLegalAccess(att)) {
					file = WebServiceUtils.convertToString(att.getInitial());
				}
				break;
			case RC_SIGNATURE:
				RCAttachment att1 = miscMgr.getRCAttachment(req.getFileId());
				if (isLegalAccess(att1)) {
					file = WebServiceUtils.convertToString(att1.getSignature());
				}
				break;
			case CATEGORY_ICON:
				file = WebServiceUtils.convertToString(loadFile("icon_category" + req.getFileId() + ".png"));
				break;
			case CATEGORY_PHOTO:
				file = WebServiceUtils.convertToString(loadFile("category" + req.getFileId() + ".png"));
				break;
			case ITEM_ICON:
				file = WebServiceUtils.convertToString(loadFile("item" + req.getFileId() + ".png"));
				break;
			case ITEM_PHOTO:
				file = WebServiceUtils.convertToString(loadFile("item" + req.getFileId() + ".png"));
				break;
			case ITEM_PHOTO_SMALL:
				file = WebServiceUtils.convertToString(loadFile("item" + req.getFileId() + ".png"));
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		resp.setFile(file);
		return resp;
	}

	@Value("/dummy")
	Resource dummyFolder;

	private byte[] loadFile(String fileName) throws IOException {
		String resPath = dummyFolder.getFile().getAbsolutePath() + File.separator + fileName;
		File file = new File(resPath);
		if (file.exists()) {
			FileInputStream fin = null;
			try {
				fin = new FileInputStream(file);
				byte fileContent[] = new byte[(int) file.length()];
				fin.read(fileContent);
				fin.close();
				return fileContent;
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@PayloadRoot(localPart = CServiceWSConstants.GET_RESOURCE_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetResourceViewResponse getResources(@RequestPayload GetResourceViewRequest req) {
		GetResourceViewResponse resp = new GetResourceViewResponse();
		List<ResourceView> rList = new ArrayList<ResourceView>(5);
		ResourceView r1 = new ResourceView();
		r1.setResourceModule(ModuleEnum.IN_ROOM_DINING.toString());
		r1.setResourceKey(ResourceKeyEnum.NON_VALID_DELIV_TIME_POPUP.toString());
		r1.setResourceType(String.class.getSimpleName());
		r1.setLanguageCode(MainEnums.Language.ENGLISH.getLangCode());
		r1.setResourceValue("Dear Guest, you are trying to order item that is not available at your requested time, please kindly select another time for delivery or select other items.");
		rList.add(r1);
		ResourceView r2 = new ResourceView();
		r2.setResourceModule(ModuleEnum.IN_ROOM_DINING.toString());
		r2.setResourceKey(ResourceKeyEnum.OUT_OF_RSV_PERIOD_POPUP.toString());
		r2.setResourceType(String.class.getSimpleName());
		r2.setLanguageCode(MainEnums.Language.ENGLISH.getLangCode());
		r2.setResourceValue("Dear Guest, we apologize that you cannot place this order as that is after you check out time.");
		rList.add(r2);
		resp.setResourceViewList(rList);
		return resp;
	}

	@Value("/dummy/menu_item_chili.png")
	Resource dummySpicy;

	@PayloadRoot(localPart = CServiceWSConstants.GET_THEME_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetThemeResponse getThemes(@RequestPayload GetThemeRequest req) {
		GetThemeResponse resp = new GetThemeResponse();

		FileInputStream fin = null;
		byte[] fileContent = null;
		try {
			fin = new FileInputStream(dummySpicy.getFile());
			fileContent = new byte[(int) dummySpicy.getFile().length()];
			fin.read(fileContent);
			fin.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		List<ThemeItem> list = new ArrayList<ThemeItem>();
		ThemeItem item1 = new ThemeItem();
		item1.setImageFile(WebServiceUtils.convertToString(fileContent));
		item1.setName(ThemeItemType.LOGO.toString());
		item1.setThemeId(1L);
		item1.setActive(true);
		list.add(item1);

		ThemeItem item2 = new ThemeItem();
		item2.setImageFile(WebServiceUtils.convertToString(fileContent));
		item2.setName(ThemeItemType.TOP_BAR.toString());
		item2.setThemeId(2L);
		item2.setActive(true);
		list.add(item2);

		ThemeItem item3 = new ThemeItem();
		item3.setImageFile(WebServiceUtils.convertToString(fileContent));
		item3.setName(ThemeItemType.SEC_BAR.toString());
		item3.setThemeId(3L);
		item3.setActive(true);
		list.add(item3);

		ThemeItem item4 = new ThemeItem();
		item4.setImageFile(WebServiceUtils.convertToString(fileContent));
		item4.setName(ThemeItemType.BODY.toString());
		item4.setThemeId(4L);
		item4.setActive(true);
		list.add(item4);

		resp.setThemeItemList(list);
		return resp;
	}
	
	@Value("/dummy/iguest_reservation.png")
	Resource dummyRes;
	
	@Value("/dummy/iguest_in_room_dining.png")
	Resource dummyInRoom;
	
	@Value("/dummy/iguest_hotel_events.png")
	Resource dummyFood;
	
	@Value("/dummy/iguest_hotel_info.png")
	Resource dummyHotel;

	@PayloadRoot(localPart = CServiceWSConstants.GET_MAIN_MENU_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetMainMenuResponse getMainMenu(@RequestPayload GetMainMenuRequest req) throws IOException {
		
		
		GetMainMenuResponse resp = new GetMainMenuResponse();
		
		List<MainMenuItemView> list = new ArrayList<MainMenuItemView>();
		
		MainMenuItemView item1 = new MainMenuItemView();
		item1.setLabel("Reservation");
		item1.setImageFile(WebServiceUtils.convertToString(loadFile("iguest_reservation.png")));
		item1.setActivate(true);
		item1.setMainMenuItemId(1L);
		item1.setType("RESERVATION");
		list.add(item1);
		
		MainMenuItemView item2 = new MainMenuItemView();
		item2.setLabel("In Room Dining");
		item2.setImageFile(WebServiceUtils.convertToString(loadFile("iguest_in_room_dining.png")));
		item2.setActivate(true);
		item2.setMainMenuItemId(2L);
		item2.setType("IN_ROOM_DINING");
		list.add(item2);
		
		MainMenuItemView item3 = new MainMenuItemView();
		item3.setLabel("Food & Beverage");
		item3.setImageFile(WebServiceUtils.convertToString(loadFile("iguest_hotel_events.png")));
		item3.setActivate(true);
		item3.setMainMenuItemId(3L);
		item3.setType("FOOD_BEVERAGE");
		list.add(item3);
		
		MainMenuItemView item4 = new MainMenuItemView();
		item4.setLabel("Hotel Info");
		item4.setImageFile(WebServiceUtils.convertToString(loadFile("iguest_hotel_info.png")));
		item4.setActivate(false);
		item4.setMainMenuItemId(4L);
		item4.setType("HOTEL_INFO");
		list.add(item4);
		
		resp.setMainMenuItemList(list );
		return resp;
	}

	@PayloadRoot(localPart = CServiceWSConstants.GET_FIELD_EDIT_REQ, namespace = CServiceWSConstants.CM_SERVICE_NAMESPACE_URI)
	@ResponsePayload
	public GetFieldEditConfResponse getFieldEditConf(@RequestPayload GetFieldEditConfRequest req) {
		GetFieldEditConfResponse resp = new GetFieldEditConfResponse();
		long orgId = CommonUtil.getWsSessionOrgId();
		long propId = CommonUtil.getWsSessionPropertyId();
		EditabilityConf conf = ccMgr.getEditabilityConf(orgId, propId, null);
		if (conf != null) {
			resp.setFieldEditList(conf.toFieldEditViewList());
		}
		return resp;
	}
}
